package com.hxh.generater.common.remote;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hxh.entity.Project;
import com.hxh.entity.output.ApiResult;
import com.hxh.entity.po.ClassInfo;
import com.hxh.util.GenUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Data
public class SpringbootRemoteUtil {
    private Project project;
    private ClassInfo classInfo;
    //是否写入文件
    private boolean writeFile;
    //远程接口地址后缀
    private String remoteUrlSuffix;
    //写入文件路径
    private String writeFilePath;
    //写入文件名
    private String writeFileName;
    //自定义代码路径 可以为空
    private String additionFilePath;
    //多数据源时用到，可为空，不需要传值，本类自动处理
    private String mutilDatasourceStr;

    /**
     * 默认流程
     *
     * @return
     * @throws IOException
     */
    public String process() throws IOException {
        List<String> additionCodeList = new ArrayList<>();
        if (StrUtil.isNotBlank(additionFilePath)) {
            additionCodeList = getAdditionCode(additionFilePath);
        }
        Map<String, Object> params = new HashMap<>();
        String mutilDatasourceStr = GenUtil.getMutilDatasourceStr(project, classInfo);
        params.put("mutilDatasourceStr", mutilDatasourceStr);
        params.put("packageName", project.getBackendProject().getProjectGroup());
        params.put("classInfo", JSONUtil.toJsonStr(classInfo));
        params.put("additionCodeList", JSONUtil.toJsonStr(additionCodeList));

        ApiResult apiResult = RemoteUtil.getCodeFromRemote(project, remoteUrlSuffix, params);
        Map<String, Object> data = (Map<String, Object>) apiResult.getData();
        String code = (String) data.get("code");
        if (writeFile) {
            File classFile = GenUtil.newFile(project, writeFilePath, writeFileName);
            RemoteUtil.writeFileToProject(code, classFile);
        }
        return code;
    }

    /**
     * 获取自定义代码
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static List<String> getAdditionCode(String filePath) throws IOException {
        List<String> additionCodeList = new ArrayList<>();
        if (StrUtil.isBlank(filePath)) {
            return additionCodeList;
        }
        File additionFile = new File(filePath);
        if (additionFile.exists() && additionFile.isDirectory()) {
            File[] additionFiles = additionFile.listFiles();
            if (additionFiles != null) {
                for (File file : additionFiles) {
                    String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
                    additionCodeList.add(content);
                }
            }
        }
        return additionCodeList;
    }

}
